package com.tianji.aigc.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.common.Constant;
import com.tianji.aigc.config.SessionProperties;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.enums.ChatTypeEnum;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.service.ChatSessionService;
import com.tianji.aigc.vo.ChatHistoryVO;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.RandomUtils;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: TODO
 * @Author: lemon
 * @CreateTime: 2025-06-06  21:34
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements ChatSessionService {

    private final SessionProperties sessionProperties;

    //使用自定义的会话记忆获取会话历史
    private final ChatMemory chatMemory;

    // 历史消息数量，默认1000条
    public static final int HISTORY_MESSAGE_COUNT = 100;

    /**
     * 新建会话
     * @param num 生成热门问题的数量，默认为 3
     */
    @Override
    public SessionVO createSession(Integer num) {
        //1.随机获取examples
        SessionVO sessionVO = BeanUtils.toBean(sessionProperties, SessionVO.class);
        sessionVO.setExamples(RandomUtil.randomEleList(sessionProperties.getExamples(), num));

        //2.随机生成sessionId
        sessionVO.setSessionId(IdUtil.fastSimpleUUID());

        //2.构建持久化对象，并持久化
        ChatSession chatSession = ChatSession.builder()
                .sessionId(sessionVO.getSessionId())
                .userId(UserContext.getUser())
                .build();
        save(chatSession);
        return sessionVO;
    }

    /**
     * 查询热门问题
     * @param num 热门问题的数量，默认为 3
     * @return
     */
    @Override
    public List<SessionVO.Example> queryHotQuestion(Integer num) {
        return RandomUtil.randomEleList(sessionProperties.getExamples(), num);
    }

    /**
     * 查询会话详情
     * @param sessionId
     * @return
     */
    @Override
    public List<ChatHistoryVO> queryChatHistory(String sessionId) {
        //1.获取用户id
        String conversationId = ChatService.getConversationId(sessionId);
        //2.从redis中获取会话历史（获取100条）
        List<Message> messages = chatMemory.get(conversationId, Constant.lastN);
        //3.转换成ChatHistoryVO
        return StreamUtil.of(messages)
                .filter(message -> message.getMessageType() == MessageType.ASSISTANT ||
                        message.getMessageType() == MessageType.USER)
                .map(message -> ChatHistoryVO.builder()
                        .content(message.getText())
                        .type(ChatTypeEnum.valueOf(message.getMessageType().name()))
                        .build())
                .toList();
    }
}
